<?php

namespace app\controllers;

// use app\parsers\DefaultParser;
use Slim;
use slimExt\base\Request;
use slimExt\base\Response;
use app\helpers\Helper;
use inhere\validate\Validation;

/**
 * Class Manager
 * @package app\controllers
 */
class Manager extends Base
{
    protected $tplPathPrefix = 'mder';

    protected $enabledItems = [];

    protected function init()
    {
        parent::init();

        $this->enabledItems = Slim::config()->get('items');
    }

    public function indexAction()
    {
        $tplVar = [
            'items' => Slim::config()->get('items'),
        ];

        // return $this->sourceAction($req);

        return $this->renderTwig('index', $tplVar);
    }

    public function projectsAction()
    {
        $valid = Validation::make($this->request->all(), [
            ['p' => 'required',]
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withRedirect('/_mder/manager')->withMessage($valid->firstError());
        }

        $project = $valid->get('p');

        $tplVar = [
            'items' => Slim::config()->get('items'),
        ];

        // ini_set('open_basedir', dirname(__FILE__) . DIRECTORY_SEPARATOR);

        // return $this->sourceAction($req);

        return $this->renderTwig('project-list', $tplVar);
    }

    /**
     * @param Request $req
     * @param Response $res
     * @return Response
     */
    public function sourceAction()
    {
        $sourcesPath = Slim::config()->get('sources.path');
        $targetPath = $basePath = Slim::alias($sourcesPath);

        $tplVar = [
            'route'   => $req->getUri()->getPath(),
            'item'    => '',
            'path'    => $req->get('path', '', 'trim'),
            'showAll' => $req->getInt('showAll', 0),
            'attrs' => DefaultParser::make()->getAttrs()
        ];

        if ( $tplVar['path'] ) {
            $tplVar['item'] = $this->findItemName($tplVar['path']);
            $targetPath .= $tplVar['path'];
        }

        $exts = $tplVar['showAll'] ? null : 'md';
        $tplVar['currentFolder'] = basename($targetPath);
        $tplVar['dataList'] = Helper::dirStruct($targetPath,true,$exts,$basePath);

// de($tplVar['dataList']);

        return $this->renderTwig('source-file', $tplVar);
    }

    /**
     * @param $path
     * @param string $default
     * @return string
     * @internal param $suffix
     */
    protected function findItemName($path, $default='')
    {
        if (!$path) {
            return $default;
        }
        // find path belongs to which item.
        $path = trim($path,'/');
        $pos  = strpos( $path ,'/');
        // $this->item = new MderItem;

        // fix: visit `/blog` should render sidebar, it real access page is `/blog/index.md`.
        if ( $pos === false ) {
            $name = $path;
        } else {
            $name = $pos>0 ? substr($path, 0, strpos($path,'/') ) : '';
        }

        return in_array( $name, $this->enabledItems) ? $name : $default;
    }

    /**
     * create item by zip
     */
    public function createByZipAction()
    {
        $valid = Validation::make($req->all(), [
            'file,name' => 'required',
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withJson(__LINE__, $valid->firstError());
        }
    }

    /**
     * create item by git
     */
    public function createByGitAction()
    {
        $valid = Validation::make($this->request->all(), [
            'url,name' => 'required',
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withJson(__LINE__, $valid->firstError());
        }

        $gitUrl = $valid->get('url');

        if ( $name = $valid->get('name') ) {
            $gitUrl .= " $name";
        }

        $sourcesPath = Slim::config()->get('sources.path');
        $targetPath = $basePath = Slim::alias($sourcesPath);

        ob_start();
        system("cd $targetPath && git clone $gitUrl");
        $result = ob_get_clean();

        // create config
        $configFile = Slim::alias('@config') . '/' . $name . '/config.yml';
        file_put_contents($configFile, 'name: ' . $name);

        return $this->response->withJson([
            'result'     => $result,
            'configFile' => $configFile,
        ]);
    }

    public function pageListAction()
    {
        // $newResponse = $this->response->withHeader('Content-type', 'application/json');
        d(__METHOD__,$this->request);
        return 234345;
    }

    const CACHE_TWIG = 'twig';
    const CACHE_FILE = 'file';
    const CACHE_LOG  = 'log';

    public function cacheClearAction()
    {
        $caches = [
            static::CACHE_TWIG => Slim::get('settings')['twigRenderer']['tpl_path'],
            static::CACHE_FILE => Slim::get('datConfig')->get('output.path'),
            static::CACHE_LOG  => Slim::get('settings')['logger']['path'],
        ];

        // $type = $req->getParseBody()['type'];
        $type = $this->request->getQueryParams()['type'];

        if (!$type || !isset($type) ) {
            return $this->response->withJson( __LINE__, 'param [type] is error!' );
        }

        return 234345;
    }

    public function configListAction()
    {
        $sourcesPath = Slim::config()->get('sources.path');
        $sourcesPath = Slim::alias($sourcesPath);

        $itemsConfig = Slim::config()->get('items');
        $items = [];

        foreach ($itemsConfig as $name => $options) {
            $items[] = [
                'name' => $name,
                'path' => isset($options['path']) ? Slim::alias($options['path']) : $sourcesPath.'/'.$name,
                'config' => $name . '/config.yml',
            ];
        }

        $viewVar = [
            'items'  => $items,
            'config' => 'config.yml',
            'attrs' => DefaultParser::make()->getAttrs()
        ];

        return $this->renderTwig('config', $viewVar);
    }

    public function editConfigAction()
    {
        $valid = Validation::make($this->request->all(), [
            'item,file,content' => 'required',
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withJson(__LINE__, $valid->firstError());
        }

        $file = $valid->get('file');
        // $configPath = Slim::alias('@config');
        $configFile = Slim::alias('@config') . '/' . $file;

        if ( !is_file($configFile) ) {
            return $this->response->withJson(__LINE__, "config file don't exists!");
        }

        $content = file_get_contents($configFile);

        return $this->response->withJson(['content' => $content]);
    }

    public function saveConfigAction()
    {
        $valid = Validation::make($this->request->all(), [
            'item,file,content' => 'required',
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withJson(__LINE__, $valid->firstError());
        }

        $file = $valid->get('file');
        // $configPath = Slim::alias('@config');
        $configFile = Slim::alias('@config') . '/' . $file;

        if ( !is_file($configFile) ) {
            return $this->response->withJson(__LINE__, "config file don't exists!");
        }
    }

    public function deleteItemAction()
    {
        $valid = Validation::make($this->request->all(), [
            'item,removeConf' => 'required',
        ])->validate();

        if ($valid->fail()) {
            return $this->response->withJson(__LINE__, $valid->firstError());
        }


    }

}